<template>
  <!-- 实测预报右侧父组件 -->
  <div class="intelligent-rainfall">
    <div class="pre-box">
      <div class="title-box">
        <span>来水预报方案信息</span>
        <div class="title-search-box">
          <span>方案名称：</span>
          <el-input v-model="state.searchName" placeholder="请输入" style="width: 200px" />
          <el-button type="primary" @click="handleSearch()">查询</el-button>
        </div>
        <div class="title-right">
          <el-button type="primary" @click="handleCreate({})">新建</el-button>
        </div>
      </div>
      <el-table
        ref="tableRef"
        :data="rainfallData"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column align="center" label="单选" width="60">
          <template #default="scope">
            <el-radio v-model="state.scid" :label="scope.row.id">{{ '' }}</el-radio>
          </template>
        </el-table-column>

        <el-table-column
          prop="sc_name"
          label="方案名称"
          align="center"
          show-overflow-tooltip
          class="left-font"
        />

        <el-table-column
          prop="start_time"
          label="降雨开始时间"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="end_time"
          label="降雨结束时间"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <div class="handle-box">
              <!-- 等于0 则未计算 -->
              <font
                v-if="scope.row.status == 0"
                :class="['iconfont', 'notStart']"
                title="计算"
                @click="handleCompute(scope.row, scope.$index)"
                >&#xe609;</font
              >
              <!-- 等于1 正在计算 -->
              <font v-if="scope.row.status == 1" :class="['iconfont']" title="计算中"
                >&#xe629;</font
              >
              <font
                v-if="scope.row.status == 2 || scope.row.status == 3"
                :class="['iconfont', 'finish']"
                title="重新计算"
                @click="handleCompute(scope.row, scope.$index)"
                >&#xe609;</font
              >
              <font class="iconfont notStart" title="编辑" @click="handleCreate(scope.row)"
                >&#xe654;</font
              >
              <font class="iconfont notStart" @click="handleDeleSc(scope.row)" title="删除"
                >&#xe662;</font
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="title">
      <span class="scDtil-font">方案详情</span
      >{{ state.scNameTitle ? '-' + state.scNameTitle : '' }}
    </div>
    <div class="bottom-box">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane label="降雨信息" name="first">
          <rainfall-info :sc-id="state.scid" ref="rainfallRef" />
        </el-tab-pane>
        <el-tab-pane label="降雨图" name="second">
          <rainfall-map :sc-id="state.scid" ref="rainMapRef" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 新建、修改弹框 -->
    <planDialog ref="planDialogRef" @handleRefresh="acceptSchemesList" />
  </div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'

import {
  // 查询方案列表
  getAirainList,
  // 删除方案
  deleteAirainList,
  // 方案计算
  calculateMore
} from '@/services/modules/intelligent-rainfall/intelligent-rainfall.js'

// 新建，修改
import planDialog from './c-cpns/planDialog/index.vue'
// 降雨信息
import rainfallInfo from './c-cpns/rainfall-info/index.vue'
//计算进度
import rainfallMap from './c-cpns/rainfall-map/index.vue'

import { useDispatchManage1, useDispatchManageRowIndex } from '@/store/modules/dispatch-manage.js'
const planDialogRef = ref(null)
const rainfallRef = ref(null)
const rainMapRef = ref(null)
const activeName = ref('first')
// ai降雨方案列表
const rainfallData = ref([])
const state = reactive({
  searchName: '',
  rowStatus: '',
  timer: null,
  statusTimer: null,
  // 方案列表选中行的索引值
  rowIndex: 0,
  modelSchems: [],
  fourAngle: {},
  scid: '',

  // 方案详情
  schemeDetail: {},
  index: 0,
  // 计算结果显隐
  tabsResult: false
})

const props = defineProps({
  watershedId: {
    type: String,
    // 默认大汶河流域
    default: ''
  },
  map: {
    type: Object,
    default: () => {}
  },
  selectName: {
    type: String,
    default: '智能降雨'
  }
})
watch(
  () => {
    props.selectName
  },
  async () => {
    if (props.selectName == '智能降雨') {
      // 获取方案列表
      rainfallData.value = []
      await acceptSchemesList()
    }
    if (rainfallData.value.length) {
      handleRowClick(rainfallData.value[0])
    } else {
      handleRowClick({})
    }
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => {
    props.watershedId
  },
  async () => {
    // 获取方案列表
    if (props.selectName == '智能降雨') {
      // 获取方案列表
      rainfallData.value = []

      await acceptSchemesList()
    }
    // 默认点击第一个方案
    if (rainfallData.value.length) {
      handleRowClick(rainfallData.value[0])
    } else {
      handleRowClick({})
    }
  },
  {
    deep: true,
    immediate: true
  }
)
//查询方案名称
function handleSearch() {
  acceptSchemesList()
}
// 点击table某一行
function handleRowClick(row) {
  rainfallRef.value.handleClearResult()
  rainMapRef.value.handleClearResult()
  // 获取计算状态
  state.rowStatus = row.status
  // 获取选中的方案名称
  state.scNameTitle = row?.sc_name
  // 选中某一行获取当前行的索引值 从0开始
  state.rowIndex = rainfallData.value.indexOf(row)
  // 切换到工程预报时 获取当前选中的方案项
  storeToRefs(useDispatchManageRowIndex()).rowIndex.value = rainfallData.value.indexOf(row)

  state.scid = row.id || ''
  storeToRefs(useDispatchManage1()).scidDialog.value = row?.id || ''
  // 当切换行 则清空轮训
  // clearInterval(state.statusTimer)
  // 判断当前行计算状态
  if (state.rowStatus == 1) {
    clearInterval(state.statusTimer)
    /**
     * 状态轮训
     */
    state.statusTimer = setInterval(async () => {
      // 每三秒刷新一次列表
      await handleRefreshList()
      // 当计算状态为完成时 停止轮巡
      if (state.rowStatus == 2 || state.rowStatus == 3) {
        // 计算完成后 获取降雨信息和降雨图的计算结果
        rainfallRef.value.handleGetAirainData()
        rainMapRef.value.handleGetAirainImg()
        clearInterval(state.statusTimer)
        state.statusTimer = null
      }
    }, 3000)
  }
}

// 新建
function handleCreate(row) {
  if (props.selectName == '智能降雨') {
    planDialogRef.value.handleOpenModal(props.watershedId, row)
  }
}

// 点击计算 控制图例显示
async function handleCompute(row, index) {
  state.index = index
  if (row.id) {
    state.scid = row.id
  }
  // 智能降雨计算
  calculateMore({ id: state.scid }).then((res) => {})
  /**
   * 状态轮训
   */
  state.statusTimer = setInterval(async () => {
    // 每三秒刷新一次列表
    await handleRefreshList()
    // 当计算状态为完成时或者计算失败 停止轮巡
    if (state.rowStatus == 2 || state.rowStatus == 3) {
      // 计算完成后 获取降雨信息和降雨图的计算结果
      rainfallRef.value.handleGetAirainData()
      rainMapRef.value.handleGetAirainImg()
      clearInterval(state.statusTimer)
      state.statusTimer = null
    }
  }, 3000)
}
// 查看计算进度时 刷新列表
async function handleRefreshList() {
  await acceptSchemesList()
  // 仍然选中记录的某一行
  handleRowClick(rainfallData.value[state.rowIndex])
}
// 获取方案列表
function acceptSchemesList() {
  if (props.selectName == '智能降雨') {
    return new Promise((resolve, reject) => {
      getAirainList({ zoneId: props.watershedId, shemeName: state.searchName }).then((res) => {
        if (res.code == 200) {
          rainfallData.value = res.data
          resolve(rainfallData.value)
        }
      })
    })
  }
}
// 删除方案
function handleDeleSc(row) {
  ElMessageBox.confirm(`是否删除`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteAirainList(row.id).then(async (res) => {
        if (res.code == 200) {
          ElMessage.success('删除成功')
          // 删除成功 重新获取方案列表
          await acceptSchemesList()
          handleRowClick(rainfallData.value[0])
        } else {
          ElMessage.warning('删除失败')
        }
      })
    })
    .catch(() => {})
}
</script>

<style lang="less" scoped>
.intelligent-rainfall {
  width: 100%;
  height: 100%;

  .pre-box {
    padding: 0 20px;
    height: 460px;

    :deep(.el-table) {
      .el-table__body {
        .el-table__row {
          .el-table_1_column_2 {
            text-align: left !important;
          }
        }
      }
    }

    .info {
      color: #9a9da2;
    }

    .primary {
      color: #4aa3ff;
    }

    .success {
      color: green;
    }

    .lrdata {
      color: blueviolet;
    }

    .title-box {
      display: flex;
      // justify-content: space-between;
      align-items: center;
      height: 50px;
      // padding: 0 20px;
      font-size: var(--header-fontsize);
      border-bottom: 1px solid var(--fold-border-color);
      margin-bottom: 20px;
      .title-search-box {
        span {
          font-size: 14px;
          margin-left: 10px;
        }
        .el-button {
          margin-left: 10px;
        }
      }
      .title-right {
        position: absolute;
        right: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .iconfont {
          color: #4ea2ec;
          cursor: pointer;
          margin-right: 30px;
        }

        .loading-map {
          margin-top: -2px !important;
        }

        .iconfont:hover {
          color: #0f83e8;
        }

        .new-file {
          font-size: 30px;
        }

        .search-file {
          font-size: 24px;
        }
      }
    }

    .el-table {
      height: calc(100% - 80px);
    }

    .handle-box {
      display: flex;

      .iconfont {
        width: 30px;
      }

      .loading-map {
        margin-top: -2px !important;
      }

      .div-width {
        width: 50px;
        height: 30px;
      }

      // justify-content: space-around;
      img {
        width: 30px;
        height: 30px;
        cursor: pointer;
      }

      .iconfont {
        width: 50px;
        font-size: 24px;
        line-height: 100%;
        font-weight: 400;
        cursor: pointer;
      }

      .loading-map {
        margin-top: -2px !important;
      }

      .notStart {
        color: #0f83e8;
      }

      .finish {
        color: green;
      }

      // .iconfont:hover {
      //   color: #1ad0095b;
      // }
    }
  }

  .title {
    line-height: 40px;
    margin: 0 20px;
    height: 40px;
    // color: black;
    font-size: var(--header-fontsize);

    color: #409eff;
    border-bottom: 1px solid var(--fold-border-color);
    margin-bottom: 20px;

    .scDtil-font {
      color: black;
    }
  }

  .bottom-box {
    // padding: 20px;
    padding: 0 20px 0px 20px;
    height: calc(100% - 520px);

    .demo-tabs {
      height: 100%;

      :deep(.el-tabs__header) {
        margin: 0;
      }

      :deep(.el-tabs__content) {
        height: calc(100% - 50px);

        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
